package com.roger.homecenterscreen.ui.components

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import com.roger.homecenterscreen.R
import kotlinx.coroutines.delay
import java.util.Calendar
import java.util.TimeZone
import java.util.Locale
import kotlin.math.cos
import kotlin.math.sin

@Composable
fun AnalogClock(
    modifier: Modifier = Modifier,
    size: Dp = 200.dp
) {
    // 使用中国时区
    val chinaTimeZone = TimeZone.getTimeZone("Asia/Shanghai")
    var currentTime by remember { mutableStateOf(Calendar.getInstance(chinaTimeZone, Locale.CHINA)) }
    val density = LocalDensity.current
    
    // 在 Composable 作用域中加载背景图片
    val backgroundImage: ImageBitmap = ImageBitmap.imageResource(R.drawable.clock_background)
    
    LaunchedEffect(Unit) {
        while (true) {
            currentTime = Calendar.getInstance(chinaTimeZone, Locale.CHINA)
            delay(1000) // 每秒更新一次
        }
    }
    
    val hour = currentTime.get(Calendar.HOUR_OF_DAY) % 12
    val minute = currentTime.get(Calendar.MINUTE)
    val second = currentTime.get(Calendar.SECOND)
    
    Box(
        modifier = modifier.size(size)
    ) {
        Canvas(
            modifier = Modifier.fillMaxSize()
        ) {
            val radius = with(density) { size.toPx() } / 2f
            val center = Offset(this.size.width / 2f, this.size.height / 2f)
            
            // 创建圆形路径用于裁剪
            val circularPath = Path().apply {
                addOval(Rect(center.x - radius, center.y - radius, center.x + radius, center.y + radius))
            }
            
            // 绘制背景图片（圆形裁剪）
            clipPath(circularPath) {
                val imageSize = minOf(backgroundImage.width, backgroundImage.height)
                
                // 计算裁剪区域（从图片中心取正方形）
                val cropSize = imageSize
                val cropLeft = (backgroundImage.width - cropSize) / 2
                val cropTop = (backgroundImage.height - cropSize) / 2
                val srcRect = Rect(
                    offset = Offset(cropLeft.toFloat(), cropTop.toFloat()),
                    size = androidx.compose.ui.geometry.Size(cropSize.toFloat(), cropSize.toFloat())
                )
                
                // 目标区域（圆形时钟区域）
                val destRect = Rect(
                    offset = Offset(center.x - radius, center.y - radius),
                    size = androidx.compose.ui.geometry.Size(radius * 2, radius * 2)
                )
                
                drawImage(
                    image = backgroundImage,
                    srcOffset = IntOffset(srcRect.left.toInt(), srcRect.top.toInt()),
                    srcSize = IntSize(srcRect.width.toInt(), srcRect.height.toInt()),
                    dstOffset = IntOffset(destRect.left.toInt(), destRect.top.toInt()),
                    dstSize = IntSize(destRect.width.toInt(), destRect.height.toInt())
                )
            }
            
            // 绘制时钟外圈
            drawCircle(
                color = Color.Black,
                radius = radius,
                center = center,
                style = Stroke(width = with(density) { 4.dp.toPx() })
            )
            
            // 绘制刻度和数字
            drawClockMarks(center, radius)
            drawClockNumbers(center, radius)
            
            // 绘制指针
            drawHourHand(center, radius, hour, minute)
            drawMinuteHand(center, radius, minute)
            drawSecondHand(center, radius, second)
            
            // 绘制中心圆点
            // 先绘制白色描边
            drawCircle(
                color = Color.White,
                radius = with(density) { 12.dp.toPx() },
                center = center
            )
            
            // 再绘制黑色中心圆点
            drawCircle(
                color = Color.Black,
                radius = with(density) { 8.dp.toPx() },
                center = center
            )
        }
    }
}

private fun DrawScope.drawClockMarks(center: Offset, radius: Float) {
    val markRadius = radius - 20f
    
    // 绘制60个刻度（包括小时和分钟刻度）
    for (i in 0 until 60) {
        val angle = i * 6.0 // 每刻度6度
        val isHourMark = i % 5 == 0 // 每5个刻度是一个小时标记
        
        val startRadius = when {
            isHourMark -> markRadius - 15f // 小时刻度较长
            else -> markRadius - 8f // 分钟刻度较短
        }
        
        val strokeWidth = if (isHourMark) 3f else 1f
        val strokeWidthWhite = strokeWidth + 2f // 白色描边更粗
        
        val startX = center.x + startRadius * cos(Math.toRadians(angle - 90)).toFloat()
        val startY = center.y + startRadius * sin(Math.toRadians(angle - 90)).toFloat()
        val endX = center.x + markRadius * cos(Math.toRadians(angle - 90)).toFloat()
        val endY = center.y + markRadius * sin(Math.toRadians(angle - 90)).toFloat()
        
        // 先绘制白色描边
        drawLine(
            color = Color.White,
            start = Offset(startX, startY),
            end = Offset(endX, endY),
            strokeWidth = strokeWidthWhite,
            cap = StrokeCap.Round
        )
        
        // 再绘制黑色主体
        drawLine(
            color = Color.Black,
            start = Offset(startX, startY),
            end = Offset(endX, endY),
            strokeWidth = strokeWidth,
            cap = StrokeCap.Round
        )
    }
}

private fun DrawScope.drawClockNumbers(center: Offset, radius: Float) {
    val numberRadius = radius - 80f // 增加距离，为更大的字体留出空间
    
    // 白色描边画笔
    val paintStroke = android.graphics.Paint().apply {
        color = Color.White.toArgb()
        textAlign = android.graphics.Paint.Align.CENTER
        textSize = 52f // 两倍大小 (26f * 2)
        isAntiAlias = true
        typeface = android.graphics.Typeface.DEFAULT_BOLD
        style = android.graphics.Paint.Style.STROKE
        strokeWidth = 8f // 描边宽度
    }
    
    // 黑色填充画笔
    val paintFill = android.graphics.Paint().apply {
        color = Color.Black.toArgb()
        textAlign = android.graphics.Paint.Align.CENTER
        textSize = 52f // 两倍大小 (26f * 2)
        isAntiAlias = true
        typeface = android.graphics.Typeface.DEFAULT_BOLD
        style = android.graphics.Paint.Style.FILL
    }
    
    // 绘制1-12的数字
    for (i in 1..12) {
        val angle = (i * 30.0) - 90.0 // 每小时30度，从12点开始
        val x = center.x + numberRadius * cos(Math.toRadians(angle)).toFloat()
        val y = center.y + numberRadius * sin(Math.toRadians(angle)).toFloat() + 16f // 调整偏移量适应更大字体
        
        // 先绘制白色描边
        drawContext.canvas.nativeCanvas.drawText(
            i.toString(),
            x,
            y,
            paintStroke
        )
        
        // 再绘制黑色填充
        drawContext.canvas.nativeCanvas.drawText(
            i.toString(),
            x,
            y,
            paintFill
        )
    }
}

private fun DrawScope.drawHourHand(center: Offset, radius: Float, hour: Int, minute: Int) {
    val hourAngle = (hour * 30.0) + (minute * 0.5) - 90 // 时针角度，包含分钟的影响
    val hourLength = radius * 0.5f
    
    rotate(hourAngle.toFloat(), center) {
        // 先绘制白色描边
        drawLine(
            color = Color.White,
            start = center,
            end = Offset(center.x + hourLength, center.y),
            strokeWidth = 10f, // 描边更粗
            cap = StrokeCap.Round
        )
        
        // 再绘制黑色时针主体
        drawLine(
            color = Color.Black,
            start = center,
            end = Offset(center.x + hourLength, center.y),
            strokeWidth = 6f,
            cap = StrokeCap.Round
        )
    }
}

private fun DrawScope.drawMinuteHand(center: Offset, radius: Float, minute: Int) {
    val minuteAngle = (minute * 6.0) - 90 // 分针角度
    val minuteLength = radius * 0.7f
    
    rotate(minuteAngle.toFloat(), center) {
        // 先绘制白色描边
        drawLine(
            color = Color.White,
            start = center,
            end = Offset(center.x + minuteLength, center.y),
            strokeWidth = 8f, // 描边更粗
            cap = StrokeCap.Round
        )
        
        // 再绘制黑色分针主体
        drawLine(
            color = Color.Black,
            start = center,
            end = Offset(center.x + minuteLength, center.y),
            strokeWidth = 4f,
            cap = StrokeCap.Round
        )
    }
}

private fun DrawScope.drawSecondHand(center: Offset, radius: Float, second: Int) {
    val secondAngle = (second * 6.0) - 90 // 秒针角度
    val secondLength = radius * 0.8f
    
    rotate(secondAngle.toFloat(), center) {
        // 先绘制白色描边
        drawLine(
            color = Color.White,
            start = center,
            end = Offset(center.x + secondLength, center.y),
            strokeWidth = 6f, // 描边更粗
            cap = StrokeCap.Round
        )
        
        // 再绘制红色秒针主体
        drawLine(
            color = Color.Red,
            start = center,
            end = Offset(center.x + secondLength, center.y),
            strokeWidth = 2f,
            cap = StrokeCap.Round
        )
    }
} 